import requests
import json
from openpyxl import Workbook
import re


def login(domain, username, password):
    # 获取cookies
    # ticket:res['data']['ticket']  任何请求都需要用到ticket
    # CSRF防止令牌:res['data']['CSRFPreventionToken']  写请求需要用到CSRF 
    login_url = domain + "api2/json/access/ticket"
    login_data = {"username":username, "password":password}
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"}
    res = requests.post(login_url, data=login_data, headers=headers).text
    res = json.loads(res)
    return res['data']['ticket'], res['data']['CSRFPreventionToken']


def get_source(ticket, CSRF, source_type, domain):
    # 获取资源信息
    get_source_url = domain + "api2/json/cluster/resources"
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    params = {'type':source_type}
    sources = requests.get(get_source_url, cookies=cookies, headers=headers, params=params).text
    sources = json.loads(sources)
    return sources


def get_ip(ticket, CSRF, nodes, qemuid, domain):
    # 获取备注信息，然后正则截取ip信息
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    get_ip_url = domain + "api2/json/nodes/" + str(nodes) + "/qemu/" + str(qemuid) + "/config"
    remarks = requests.get(get_ip_url, cookies=cookies, headers=headers).text
    remarks = json.loads(remarks)["data"]
    if "description" in remarks.keys():
        remarks = remarks["description"]
    else:
        return "没有备注"
    # print(remarks)
    ip = re.search(r"ip[^\d]*((\d{1,3}\.){3}\d{1,3})", remarks, re.I)
    # print(ip, type(ip))
    if ip:
        return ip.group(1)
    else:
        return "没有匹配到"


def get_nodes_info(ticket, CSRF, nodename):
    get_nodes_url = domain + "api2/json/nodes/" + nodename + "/status"
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    info = requests.get(get_nodes_url, cookies=cookies, headers=headers).text
    info = json.loads(info)
    # print(info)
    info = {x:info['data'][x] for x in info['data'].keys() if x == "cpu" or x == "memory"}
    memory = str(round(info['memory']['total']/1024/1024/1024, 2)) + "G/" + str(round(info['memory']['used']/1024/1024/1024, 2)) + "G/" + \
        str(round(info['memory']['used']/info['memory']['total']*100, 2)) + "%"
    cpu = str(round(info['cpu']*100, 2)) + "%"
    return memory, cpu


def get_nodes_storage(ticket, CSRF, nodename):
    get_storage_url = domain + "api2/json/nodes/" + nodename + "/storage"
    cookies = {'PVEAuthCookie':ticket}
    headers = {'CSRFPreventionToken':CSRF}
    info = requests.get(get_storage_url, cookies=cookies, headers=headers).text
    info = json.loads(info)
    # storage = 
    print(info)

domain = "https://pve.smyjf.cn/"
username = "root@pam"
password = "eG4vue!paA"

# domain = "https://prdpve.smyoa.com/"
# username = "root@pam"
# password = "Smy12345"

# domain = "https://pve01.smyoa.com/"
# username = "root@pam"
# password = "pre_siy_pve@20200602!"

ticket, CSRF = login(domain, username, password)

# get_nodes_storage(ticket, CSRF, "smy05")


sources = get_source(ticket,CSRF,'vm', domain)["data"]
sources_dict = {}
# 根据节点区分虚拟机，节点名为key，vm信息（字典类型）为value。
for i in sources:
    if i['node'] in sources_dict.keys():
        sources_dict[i['node']].append(i)
    else:
        sources_dict[i['node']] = [i]

# 写入excel
wb = Workbook()  # 创建workbook实例
ws = wb.create_sheet("资产")  # 创建一个sheets表单
ws['a2'] = "node"
ws['b2'] = "id"
ws['c2'] = "ip"
ws['d2'] = "主机名"
ws['e2'] = "cpu"
ws['f2'] = "内存"
ws['g2'] = "磁盘"
ws['h2'] = "状态"
ws['i2'] = "node内存"
ws['j2'] = "node_cpu使用率"
ws.merge_cells(start_row=1, start_column=2, end_row=1, end_column=8)
ws.merge_cells(start_row=1, start_column=9, end_row=1, end_column=11)
ws.cell(row=1, column=2, value="虚拟机配置信息")
ws.cell(row=1, column=9, value="节点资源信息")
node_now = 3
for i in sources_dict.keys():
    node_start = node_now
    n_memory, n_cpu = get_nodes_info(ticket, CSRF, i)
    for vm in sources_dict[i]:

        ws.cell(row=node_now, column=2, value=vm['vmid'])
        ip = get_ip(ticket, CSRF, i , vm['vmid'], domain)
        ws.cell(row=node_now, column=3, value=ip)
        ws.cell(row=node_now, column=4, value=vm['name'])
        ws.cell(row=node_now, column=5, value=vm['maxcpu'])
        ws.cell(row=node_now, column=6, value=str(vm['maxmem']//(1024**3))+"G")
        ws.cell(row=node_now, column=7, value=str(vm['maxdisk']//(1024**3))+"G")
        ws.cell(row=node_now, column=8, value=vm['status'])
        node_now += 1

    ws.merge_cells(start_row=node_start, start_column=1, end_row=node_now-1, end_column=1)
    ws.merge_cells(start_row=node_start, start_column=9, end_row=node_now-1, end_column=9)
    ws.merge_cells(start_row=node_start, start_column=10, end_row=node_now-1, end_column=10)
    ws.cell(row=node_start, column=1, value=i)
    ws.cell(row=node_start, column=9, value=n_memory)
    ws.cell(row=node_start, column=10, value=n_cpu)
wb.save('资产.xlsx')
